<?php


namespace app\admin\controller\consult;

use app\admin\model\ConsultMessage;
use app\admin\model\User;
use app\admin\service\ExcelService;
use app\admin\service\SmsService;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\service\CommonService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\App;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\annotation\ControllerAnnotation;
use think\facade\Db;
use think\Model;

/**
 * Class Goods
 * @package app\admin\controller\consult
 * @ControllerAnnotation(title="投诉建议管理")
 */
class Message extends AdminController
{

    use Curd;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new ConsultMessage();
    }

    /**
     * @NodeAnotation(title="投诉建议列表")
     */
    public function index()
    {
        $townshipList=[];
        if($this->admin['type']==7){
            //乡村振兴局
            $townshipList=Db::connect('common')->table('ea_conf_area')->where(['level'=>3])->select()->toArray();
        }
        $townshipSelect=[];
        foreach ($townshipList as $k=>$v){
            $townshipSelect[$v['id']]=$v['name'];
        }
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            foreach ($where as $k=>$v){
                if($v[0]=='status'){
                    if($v[2]==0){
                        //已回复
                        $where[$k]=['reply','exp',Db::raw('is not null')];
                    }else{
                        //未回复
                        $where[$k]=['reply','exp',Db::raw('is null')];
                    }
                }
            }
            $admin=session('admin');
            if($admin['type']==3){
                //乡镇管理员
                $where[]=['township','=',$admin['area_id']];
            }
            $count = $this->model->where($where)->count();
            $list = $this->model->where($where)->page($page, $limit)->order($this->sort)->select();
            foreach ($list as $k=>$v){
                $list[$k]=$this->resetInfo($v);
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign([
            'townshipSelect'=>json_encode($townshipSelect,true),
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="回复")
     */
    public function reply($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'reply|回复内容'   => 'require',
            ];
            $this->validate($post, $rule);
            $post=$this->handlePostData($post);
            //$post['is_read']=1;
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                //发送短信 留言回复发送给用户
                /*$user=Db::table('ea_user')->where(['id'=>$row['user_id']])->field('username')->find();
                if(!empty($user)&&!empty($user['phone'])){
                    SmsService::sendMes(15,[$user['phone']],['name'=>$user['name']]);
                }*/
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign([
            'id'          => $id,
            'row'         => $row,
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    private function handlePostData($data){
        $data['reply_time']=time();
        return $data;
    }

    private function resetInfo($data){
        if($data){
            $data['type_text'] = $data['type'] == 1 ? "投诉" : "建议";
            if($data['user_id']){
                $userM=new User();
                $user=$userM->where(['id'=>$data['user_id']])->field('username,township')->find();
                $data['username'] = $data['is_nm'] == 1 ? '匿名' : $user['username'];
                $data['township_text']='';
                if(!empty($user['township']))$data['township_text']=$this->getArea($user['township'])['name'];
            }
            $data['status_text']='未回复';
            if(!empty($data['reply_time'])){
                $data['status_text']='已回复';
            }
            $data['reply_time_text']=!empty($data['reply_time'])?date('Y-m-d H:i:s',$data['reply_time']):'';
        }
        return $data;
    }
}